package zero.tech.games.log.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

@Component
public class TxUtil {
	private static final Logger logger=LoggerFactory.getLogger(TxUtil.class);
	@Autowired
	private PlatformTransactionManager tx;
	
	public static interface TxMethod{
		public void txRun() throws Exception;
	}
	
	public boolean txSurport(TxMethod txMethod) {
		DefaultTransactionDefinition def = new DefaultTransactionDefinition();
		def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
		TransactionStatus status = tx.getTransaction(def);
		try {
			txMethod.txRun();
			tx.commit(status);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("显式事务失败,进行回滚操作");
			tx.rollback(status);
			return false;
		}
	}
}
